#!/usr/bin/env python3
# isort: skip
import os
import sys

# Python <3.4 does not have pathlib
if sys.version_info.major != 3 or sys.version_info.minor < 7:
    print("ERROR! Make sure you use Python 3.7+ !!")
    sys.exit(1)

import subprocess
from os import execv
from pathlib import Path

AIRFLOW_SOURCES_DIR = Path(__file__).parent.resolve()
BUILD_DIR = AIRFLOW_SOURCES_DIR / ".build"
BUILD_BREEZE_DIR = BUILD_DIR / "breeze2"
BUILD_BREEZE_CFG_SAVED = BUILD_BREEZE_DIR / "setup.cfg.saved"
BUILD_BREEZE_VENV_DIR = BUILD_BREEZE_DIR / "venv"
BUILD_BREEZE_VENV_BIN_DIR = BUILD_BREEZE_VENV_DIR / "bin"
BUILD_BREEZE_VENV_PIP = BUILD_BREEZE_VENV_BIN_DIR / "pip"
BUILD_BREEZE_VENV_BREEZE = BUILD_BREEZE_VENV_BIN_DIR / "Breeze2"

BREEZE_SOURCE_PATH = AIRFLOW_SOURCES_DIR / "dev" / "breeze"
BREEZE_SETUP_CFG_PATH = BREEZE_SOURCE_PATH / "setup.cfg"

BUILD_BREEZE_DIR.mkdir(parents=True, exist_ok=True)


def needs_installation() -> bool:
    """Returns true if Breeze's virtualenv needs (re)installation"""
    if not BUILD_BREEZE_VENV_DIR.exists() or not BUILD_BREEZE_CFG_SAVED.exists():
        return True
    return BREEZE_SETUP_CFG_PATH.read_text() != BUILD_BREEZE_CFG_SAVED.read_text()


def save_config():
    """Saves cfg file to virtualenv to check if there is a need for reinstallation of the virtualenv"""
    BUILD_BREEZE_CFG_SAVED.write_text(BREEZE_SETUP_CFG_PATH.read_text())


if needs_installation():
    print(f"(Re)Installing Breeze's virtualenv in {BUILD_BREEZE_VENV_DIR}")
    BUILD_BREEZE_VENV_DIR.mkdir(parents=True, exist_ok=True)
    subprocess.run([sys.executable, "-m", "venv", f"{BUILD_BREEZE_VENV_DIR}"], check=True)
    subprocess.run(
        [f"{BUILD_BREEZE_VENV_PIP}", "install", "--upgrade", "-e", "."], cwd=BREEZE_SOURCE_PATH, check=True
    )
    save_config()

if os.name == 'nt':
    # This is the best way of running it on Windows, though it leaves the original process hanging around
    subprocess.run([f"{BUILD_BREEZE_VENV_BREEZE}.exe"] + sys.argv[1:], check=True)
else:
    execv(f"{BUILD_BREEZE_VENV_BREEZE}", [f"{BUILD_BREEZE_VENV_BREEZE}"] + sys.argv[1:])
